/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package negocio;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
//import java.sql.Date;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.transaction.UserTransaction;

/**
 *
 * @author user
 */
@Entity
@Table(name = "tarea")
@NamedQueries({@NamedQuery(name = "Tarea.findAll", query = "SELECT t FROM Tarea t"), @NamedQuery(name = "Tarea.findByIdTarea", query = "SELECT t FROM Tarea t WHERE t.idTarea = :idTarea"), @NamedQuery(name = "Tarea.findByNombre", query = "SELECT t FROM Tarea t WHERE t.nombre = :nombre"), @NamedQuery(name = "Tarea.findByEstado", query = "SELECT t FROM Tarea t WHERE t.estado = :estado"), @NamedQuery(name = "Tarea.findByTipo", query = "SELECT t FROM Tarea t WHERE t.tipo = :tipo"), @NamedQuery(name = "Tarea.findByImportancia", query = "SELECT t FROM Tarea t WHERE t.importancia = :importancia"), @NamedQuery(name = "Tarea.findByFechaInicio", query = "SELECT t FROM Tarea t WHERE t.fechaInicio = :fechaInicio"), @NamedQuery(name = "Tarea.findByFechaFinal", query = "SELECT t FROM Tarea t WHERE t.fechaFinal = :fechaFinal"), @NamedQuery(name = "Tarea.findBySitio", query = "SELECT t FROM Tarea t WHERE t.sitio = :sitio"), @NamedQuery(name = "Tarea.findByLatitud", query = "SELECT t FROM Tarea t WHERE t.latitud = :latitud"), @NamedQuery(name = "Tarea.findByLongitud", query = "SELECT t FROM Tarea t WHERE t.longitud = :longitud"), @NamedQuery(name = "Tarea.findByTag1", query = "SELECT t FROM Tarea t WHERE t.tag1 = :tag1"), @NamedQuery(name = "Tarea.findByTag2", query = "SELECT t FROM Tarea t WHERE t.tag2 = :tag2"), @NamedQuery(name = "Tarea.findByTag3", query = "SELECT t FROM Tarea t WHERE t.tag3 = :tag3"), @NamedQuery(name = "Tarea.findByUrl1", query = "SELECT t FROM Tarea t WHERE t.url1 = :url1"), @NamedQuery(name = "Tarea.findByUrl2", query = "SELECT t FROM Tarea t WHERE t.url2 = :url2"), @NamedQuery(name = "Tarea.findByUrl3", query = "SELECT t FROM Tarea t WHERE t.url3 = :url3"), @NamedQuery(name = "Tarea.findByDescripcion", query = "SELECT t FROM Tarea t WHERE t.descripcion = :descripcion")})
public class Tarea implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_tarea")
    private Integer idTarea;
    @Basic(optional = false)
    @Column(name = "nombre")
    private String nombre;
    @Basic(optional = false)
    @Column(name = "estado")
    private String estado;
    @Basic(optional = false)
    @Column(name = "tipo")
    private String tipo;
    @Basic(optional = false)
    @Column(name = "importancia")
    private String importancia;
    @Basic(optional = false)
    @Column(name = "fecha_inicio")
    @Temporal(TemporalType.TIMESTAMP)
    private Date fechaInicio;
    @Basic(optional = false)
    @Column(name = "fecha_final")
    @Temporal(TemporalType.TIMESTAMP)
    private Date fechaFinal;
    @Column(name = "sitio")
    private String sitio;
    @Column(name = "latitud")
    private String latitud;
    @Column(name = "longitud")
    private String longitud;
    @Column(name = "tag1")
    private String tag1;
    @Column(name = "tag2")
    private String tag2;
    @Column(name = "tag3")
    private String tag3;
    @Column(name = "url1")
    private String url1;
    @Column(name = "url2")
    private String url2;
    @Column(name = "url3")
    private String url3;
    @Column(name = "descripcion")
    private String descripcion;

    public Tarea() {
    }

    public Tarea(Integer idTarea) {
        this.idTarea = idTarea;
    }

    public Tarea(Integer idTarea, String nombre, String estado, String tipo, String importancia, Date fechaInicio, Date fechaFinal) {
        this.idTarea = idTarea;
        this.nombre = nombre;
        this.estado = estado;
        this.tipo = tipo;
        this.importancia = importancia;
        this.fechaInicio = fechaInicio;
        this.fechaFinal = fechaFinal;
    }

    public Integer getIdTarea() {
        return idTarea;
    }

    public void setIdTarea(Integer idTarea) {
        this.idTarea = idTarea;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

    public String getImportancia() {
        return importancia;
    }

    public void setImportancia(String importancia) {
        this.importancia = importancia;
    }

    public Date getFechaInicio() {
        return fechaInicio;
    }

    public void setFechaInicio(Date fechaInicio) {
        this.fechaInicio = fechaInicio;
    }

    public Date getFechaFinal() {
        return fechaFinal;
    }

    public void setFechaFinal(Date fechaFinal) {
        this.fechaFinal = fechaFinal;
    }

    public String getSitio() {
        return sitio;
    }

    public void setSitio(String sitio) {
        this.sitio = sitio;
    }

    public String getLatitud() {
        return latitud;
    }

    public void setLatitud(String latitud) {
        this.latitud = latitud;
    }

    public String getLongitud() {
        return longitud;
    }

    public void setLongitud(String longitud) {
        this.longitud = longitud;
    }

    public String getTag1() {
        return tag1;
    }

    public void setTag1(String tag1) {
        this.tag1 = tag1;
    }

    public String getTag2() {
        return tag2;
    }

    public void setTag2(String tag2) {
        this.tag2 = tag2;
    }

    public String getTag3() {
        return tag3;
    }

    public void setTag3(String tag3) {
        this.tag3 = tag3;
    }

    public String getUrl1() {
        return url1;
    }

    public void setUrl1(String url1) {
        this.url1 = url1;
    }

    public String getUrl2() {
        return url2;
    }

    public void setUrl2(String url2) {
        this.url2 = url2;
    }

    public String getUrl3() {
        return url3;
    }

    public void setUrl3(String url3) {
        this.url3 = url3;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    /**************************************************************/

    public Tarea(Integer idTarea,String nombre, String estado, String tipo, String importancia, String fechaInicio, String fechaFinal, String latitud, String longitud, String tag1, String tag2, String tag3, String url1, String url2, String url3, String descripcion) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd");

        this.idTarea = idTarea;this.nombre = nombre;
        this.estado = estado;
        this.tipo =tipo;
        this.importancia = importancia;
        try{

        /*SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");*/
       /* GregorianCalendar greCal = new GregorianCalendar();
        greCal.setTime( formatter.parse( "2005-12-31" ) );

        Date d= greCal.getGregorianChange();
        System.out.println("en tarea"+greCal.toString());*/
        this.fechaInicio = formatoDelTexto.parse(fechaInicio);
        this.fechaFinal = formatoDelTexto.parse(fechaFinal);
        System.out.println("en tarea"+this.fechaInicio);
        }catch(Exception e){
        throw new RuntimeException(e);
        }
        this.sitio = "";
        this.latitud = latitud;
        this.longitud = longitud;
        this.tag1 = tag1;
        this.tag2 = tag2;
        this.tag3 = tag3;
        this.url1 = url1;
        this.url2 = url2;
        this.url3 = url3;
        this.descripcion = descripcion;
    }

   /***************************************************************/

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idTarea != null ? idTarea.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Tarea)) {
            return false;
        }
        Tarea other = (Tarea) object;
        if ((this.idTarea == null && other.idTarea != null) || (this.idTarea != null && !this.idTarea.equals(other.idTarea))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "negocio.Tarea[idTarea=" + idTarea + "]";
    }


    public void persist(Object object) {
        /* Add this to the deployment descriptor of this module (e.g. web.xml, ejb-jar.xml):
         * <persistence-context-ref>
         * <persistence-context-ref-name>persistence/LogicalName</persistence-context-ref-name>
         * <persistence-unit-name>UPersistencia</persistence-unit-name>
         * </persistence-context-ref>
         * <resource-ref>
         * <res-ref-name>UserTransaction</res-ref-name>
         * <res-type>javax.transaction.UserTransaction</res-type>
         * <res-auth>Container</res-auth>
         * </resource-ref> */
        try {
            Context ctx = new InitialContext();
            UserTransaction utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }
/***************************************insertar a la base******************/
     
     
     public boolean insertar(String fechaInicial,String fechaFinal){
         java.sql.Date fechaIni=null;
         java.sql.Date fechaFin=null;
        boolean estado;
                                                                                                                                                                                                                                                                                                                                                               //d_Tarea, nombre, estado, tipo, importancia, fecha_inicio, fecha_final, latitud, longitud, tag1, tag2, tag3, url1, url2, url3, descripcion                                                    
        //String queryString = "insert into evento (id_evento,nombre,descripcion,id_responsable,id_local,id_entidad,id_categoria,costo,cupo_max,hora_inicio,hora_fin) values("+this.getIdEvento()+",'"+this.getNombre()+"','"+this.getDescripcion()+"',"+idresp+","+idloc+","+ident+","+idcat+","+costo+","+cupo_max+",'"+hora_inicio+"','"+hora_fin+"')";
        try {
            SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd");
             java.util.Date fechaIn = formatoDelTexto.parse(fechaInicial);
             java.util.Date fechaFi = formatoDelTexto.parse(fechaFinal);
             fechaIni = new java.sql.Date(fechaIn.getTime());
             fechaFin = new java.sql.Date(fechaFi.getTime());
             System.out.println("en insertar: "+fechaIni+","+fechaFin);
             String queryString = "insert into tarea (id_Tarea, nombre, estado, tipo, importancia, sitio, fecha_inicio, fecha_final, latitud, longitud, tag1, tag2, tag3, url1, url2, url3, descripcion) values("+this.getIdTarea()+",'"+this.getNombre()+"','"+this.getEstado()+"','"+this.getTipo()+"','"+this.getImportancia()+"','"+this.getSitio()+"','"+fechaIni+"','"+fechaFin+"','"+this.getLatitud()+"','"+this.getLongitud()+"','"+this.getTag1()+"','"+this.getTag2()+"','"+this.getTag3()+"','"+this.getUrl1()+"','"+this.getUrl2()+"','"+this.getUrl3()+"','"+this.getDescripcion()+"')";
             System.out.println("query :"+ queryString);

            Context ctx = new InitialContext();
            
            UserTransaction utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");
            utx.begin();
            
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString);
            
            q.executeUpdate();
            
            utx.commit();
            estado=true;
        } catch (Exception e) {
            estado=false;
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            System.out.println("error al insertar"+e.getMessage());
            throw new RuntimeException(e);

        }
        return estado;
    }


     public boolean insertar(int id_usuario){

         boolean guardo;
             String queryString = "insert into rel_usuario_tarea (id_usuario,id_tarea) values("+id_usuario+","+this.getIdTarea()+")";
             System.out.println("query :"+ queryString);
                                                                                                                                                                                                                                                                                                                                                  //d_Tarea, nombre, estado, tipo, importancia, fecha_inicio, fecha_final, latitud, longitud, tag1, tag2, tag3, url1, url2, url3, descripcion
        //String queryString = "insert into evento (id_evento,nombre,descripcion,id_responsable,id_local,id_entidad,id_categoria,costo,cupo_max,hora_inicio,hora_fin) values("+this.getIdEvento()+",'"+this.getNombre()+"','"+this.getDescripcion()+"',"+idresp+","+idloc+","+ident+","+idcat+","+costo+","+cupo_max+",'"+hora_inicio+"','"+hora_fin+"')";
        try {

            Context ctx = new InitialContext();

            UserTransaction utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");
            utx.begin();

            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString);

            q.executeUpdate();

            utx.commit();
            guardo=true;
        } catch (Exception e) {
            guardo=false;
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            System.out.println("error al insertar"+e.getMessage());
            throw new RuntimeException(e);

        }
        return guardo;
    }
     /*********************************************************************************/

     public static List<Tarea> consultarTareasPendientes(int id) {

        String queryString = "select * from rel_usuario_tarea rel,tarea t where rel.id_usuario='"+id+"' and rel.id_tarea = t.id_tarea and t.estado='pendiente'";

        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString,Tarea.class);
            List<Tarea> resultado =  (List<Tarea>)q.getResultList();
            return(resultado);
        } catch (Exception e) {
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }

     /******************* Highlight Calendario **************************/
    public static List<Tarea> consultarFechasTareas(int id) {

        String queryString = "select * from rel_usuario_tarea rel,tarea t where rel.id_usuario='"+id+"' and rel.id_tarea = t.id_tarea ";

        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString,Tarea.class);
            List<Tarea> resultado =  (List<Tarea>)q.getResultList();

            //System.out.println(resultado);
            return(resultado);
        } catch (Exception e) {
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }

    /******************* Cambiar importancia en la base **************************/

    public static void cambiarImportancia(int id) {

        String queryString = "select * from rel_usuario_tarea rel,tarea t where rel.id_usuario='"+id+"' and rel.id_tarea = t.id_tarea and t.estado='pendiente'";

        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString,Tarea.class);
            List<Tarea> resultado =  (List<Tarea>)q.getResultList();
            //return(resultado);
        } catch (Exception e) {
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }
    /*******METODO PARA OBTENER EL ID DE LA NUEVA TAREA QUE VA SER INGRESADA EN LA BASE*/
     public static int obtener_new_id(){
       String queryString = "SELECT id_tarea FROM `tarea`";
           Integer mayor=0,tmp=0;
        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString,Tarea.class);
             List<Tarea> resultado = (List<Tarea>)q.getResultList();

            for(int i=0;i<resultado.size();i++){
                Tarea ev=(Tarea)resultado.get(i);
                tmp=ev.getIdTarea();
                if(tmp>mayor)
                    mayor=tmp;
            }
        } catch (Exception e) {
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }

            return Integer.valueOf(mayor)+1;
    }


      public static List<Tarea> consultarTareasPendientes() {

        String queryString = "select * from tarea t where  t.estado='pendiente'";

        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString,Tarea.class);
            List<Tarea> resultado =  (List<Tarea>)q.getResultList();
            return(resultado);
        } catch (Exception e) {
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }


     /*********METODO PARA CONSULTAR LOS AÑOS DE LAS TAREAS TERMINADAS*/
     public static ArrayList consultarAño() {

        String queryString = "SELECT *FROM  tarea t ";

        try {
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
            Query q = (Query)em.createNativeQuery(queryString,Tarea.class);
            ArrayList resultado =  (ArrayList)q.getResultList();

            //System.out.println(resultado);
            return(resultado);
        } catch (Exception e) {
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }

     public static String verificar(int valor)
     {
         String xml="<respuesta>"+
                "<valor>"+valor+"</valor>"+
            "</respuesta>";
         return xml;

     }

}
